package v1

import (
	"daily-blog/global"
	"daily-blog/model"
	"daily-blog/pkg"
	"daily-blog/service"
	"github.com/gin-gonic/gin"
)

func CreatePost(c *gin.Context) {
	var reqPost model.RequestPost
	err := c.ShouldBind(&reqPost)
	if err != nil {
		pkg.Fail(c)
		global.GVA_LOG.Info(err.Error())
		return
	}
	if ok := service.CreatePostService(
		reqPost.Title,
		reqPost.Desc,
		reqPost.Content,
		reqPost.Author,
		reqPost.CategoryId,
		reqPost.CategoryName,
		reqPost.Tags,
	); !ok {
		pkg.Fail(c)
		return
	}
	pkg.Ok(c)

}
func DeletePost(c *gin.Context) {
	postId := c.PostForm("post_id")
	if postId == "" {
		pkg.FailWithMessage("文章未选中", c)
		return
	}
	if ok := service.DeletePostByIDService(postId); !ok {
		pkg.Fail(c)
		return
	}
	pkg.Ok(c)
}
func UpdatePost(c *gin.Context) {
	var updatePost model.RequestUpdatePost
	if err := c.ShouldBindJSON(&updatePost); err != nil {
		pkg.FailWithMessage("参数绑定错误", c)
		global.GVA_LOG.Error(err.Error())
		return
	}
	ok := service.UpdatePostByIdService(updatePost.PostId, updatePost.Title, updatePost.Desc, updatePost.Content, updatePost.CategoryId,
		updatePost.CategoryName, updatePost.Tags)
	if !ok {
		pkg.Fail(c)
		return
	}
	pkg.Ok(c)
}
func GetPost(c *gin.Context) {
	postId := c.Query("post_id")
	if postId == "" {
		pkg.FailWithMessage("文章id为空", c)
		return
	}
	content, ok := service.GetPostByIDService(postId)
	if !ok {
		pkg.Fail(c)
		return
	}
	pkg.OkWithData(gin.H{"content": content}, c)
}
func GetPostList(c *gin.Context) {
	PostList, ok := service.GetPostListService()
	if !ok {
		pkg.Fail(c)
		return
	}
	pkg.OkWithData(PostList, c)
}
func GetPostListWithCategory(c *gin.Context) {
	categoryId := c.Query("category_id")
	if categoryId == "" {
		pkg.FailWithMessage("参数错误，目录id为空", c)
		return
	}
	postList, ok := service.GetPostListByCategoryId(categoryId)
	if !ok {
		pkg.Fail(c)
		return
	}
	pkg.OkWithData(postList, c)
}
func GetPostListWithTag(c *gin.Context) {
	tagId := c.Query("tag_id")
	if tagId == "" {
		pkg.FailWithMessage("参数错误，tag_id为空", c)
		return
	}

	postList, ok := service.GetPostListByTagId(tagId)
	if !ok {
		pkg.Fail(c)
		return
	}

	pkg.OkWithData(postList, c)
}
func AddLike(c *gin.Context) {
	postId := c.Query("post_id")
	if postId == "" {
		pkg.FailWithMessage("文章id为空", c)
		return
	}
	// 增加点赞
	if ok := service.AddCount(postId, 1); !ok {
		pkg.Fail(c)
		return
	}
	pkg.Ok(c)

}
